package com.sk.skplanet.commute.parser;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.sk.skplanet.commute.vo.GetRouteByStationVo;

public class GetRouteByStationParser extends SeoulBusAPIParser {
	private List<GetRouteByStationVo> result;
	
	public GetRouteByStationParser(String rawData) {
		super(rawData);
	}

	@Override
	public List<GetRouteByStationVo> parse() {
		result = new ArrayList<GetRouteByStationVo>();
		
		try {
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser = parserCreator.newPullParser();
	
			parser.setInput(new StringReader(rawData));
			parser.next();
			
			int parserEvent = parser.getEventType();
	
			String tagName = "";
			GetRouteByStationVo objectToAdd = null;
			
			while(parserEvent != XmlPullParser.END_DOCUMENT) {
				switch (parserEvent) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					tagName = parser.getName();
					if(tagName.equals("itemList"))
						objectToAdd = new GetRouteByStationVo();
					break;
				case XmlPullParser.END_TAG:
					if(parser.getName().equals("itemList") && objectToAdd != null) {
						result.add(objectToAdd);
						objectToAdd = null;
					}
					break;
				case XmlPullParser.TEXT:
					String text = parser.getText();
					
					if(objectToAdd != null) {
						if(tagName.equals("busRouteId"))
							objectToAdd.setBusRouteId(text);
						else if(tagName.equals("busRouteNm"))
							objectToAdd.setBusRouteNm(text);
						else if(tagName.equals("busRouteType"))
							objectToAdd.setBusRouteType(text);
						else if(tagName.equals("firstBusTm"))
							objectToAdd.setFirstBusTm(text);
						else if(tagName.equals("firstBusTmLow"))
							objectToAdd.setFirstBusTmLow(text);
						else if(tagName.equals("lastBusTm"))
							objectToAdd.setLastBusTm(text);
						else if(tagName.equals("lastBusTmLow"))
							objectToAdd.setLastBusTmLow(text);
						else if(tagName.equals("length"))
							objectToAdd.setLength(text);
						else if(tagName.equals("nextBus")) {
							if(Integer.parseInt(text) < 0) {
								objectToAdd = null;
								break;
							}
							objectToAdd.setNextBus(text);
						}
						else if(tagName.equals("stBegin"))
							objectToAdd.setStBegin(text);
						else if(tagName.equals("stEnd"))
							objectToAdd.setStEnd(text);
						else if(tagName.equals("term"))
							objectToAdd.setTerm(text);
					}
	
					break;
				}
	
				parserEvent = parser.next();
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}

}
